package sf.database.util;

import sf.database.dialect.DBDialect;

/**
 * 简易SQL模板
 */
public class SimpleSQLTemplate {

    /**
     * 使用模板包装
     * @param name
     * @return
     */
    public static String wrapperTable(String name) {
        return '[' + name + ']';
    }

    /**
     * 使用模板包装
     * @param name
     * @return
     */
    public static String wrapperColumn(String name) {
        return '[' + name + ']';
    }

    /**
     * 模板关键字替换<br>
     * 该方法主要是用于数据库方言中的关键字替换.
     * @param dialect
     * @param content
     * @return
     */
    public static String unwrapper(DBDialect dialect, String content) {
        StringBuilder sb = new StringBuilder();
        StringBuilder inner = new StringBuilder();
        boolean replaceFlag = false;
        for (int i = 0; i < content.length(); i++) {
            char c = content.charAt(i);
            if (c == '[') {
                replaceFlag = true;
                inner.delete(0, inner.length());
                continue;
            } else if (replaceFlag && c == ']') {
                String word = inner.toString();
                word = dialect.wrapKeyword(word);
                sb.append(word);
                replaceFlag = false;
                continue;
            }
            if (replaceFlag) {
                inner.append(c);
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
}
